<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { useCodeStore } from "@/stores/code.js";
import picView from "../../components/pic/index.vue";
import {
  appCategory,
  supplierSelector,
  productCreate,
  appProductDetail,
  appProductDisable,
  appProductEnable,
  productUpdate,
  appProductCode,
  appUnit,
} from "@/services/goods";
import { appSelectorAll } from "@/services/stocktaking";
import { appShopSelector } from "@/services/transfer";

import { base_URL } from "@/utils/http";
import homeStart from "@/pages/goods/static/sacd.png";
import { stockCounterStore } from "@/stores/stock";

const stockObj = stockCounterStore();

const showSelect = ref("");
const showInShop = ref(false);
const ShopList = ref([]);

if (uni.getStorageSync("selectShopType")) {
  showSelect.value = uni.getStorageSync("selectShopType");
}

// import tabbarView from "../components/tabbar.vue";
const codeStore = useCodeStore();

console.log("codeStore", codeStore.code);

const formMode = ref(null);
const form = ref({
  name: "",
  scId: "",
  takeType: "",
});
const checked = ref(false);
const showBarCode = ref(false);
//类型
const type = ref("");
// id
const id = ref("");
const barCodeStr = ref("");

onLoad((options) => {
  console.log(options);
  type.value = options.type ? options.type : "";
  id.value = options.id ? options.id : "";
  if (id.value) {
    getProduceDet();
  }
  codeStore.setcode("");
  // getAppUnit();
  getAppSelectorAll();
  // getAppShopSelector();
});

onShow(() => {
  if (codeStore.code) {
    if (showBarCode.value) {
      selectBarCodeItem.value = codeStore.code;
    } else {
      form.value.barCode = codeStore.code;

      if (type.value != "add") {
        form.value.barCodeList[0] = codeStore.code;
      }
    }
  }
  console.log(codeStore.code);

  // showToast("扫码结果" + codeStore.code);
});
const name = ref("");
const getAppSelectorAll = async () => {
  let res = await appSelectorAll({
    name: name.value,
    pageIndex: 1,
    pageSize: 9999,
  });
  // ShopList.value = res.data.datas;
  ShopList.value = res.data.datas;
  if (!name.value && res.data.datas.length == 1) {
    selectItem.value = res.data.datas[0];
    selectid.value = res.data.datas[0].id;
    selename.value = res.data.datas[0].name;
    form.value.scId = res.data.datas[0].id;
  }
};
const search = async () => {
  getAppSelectorAll();
};

// 门店选择
const getAppShopSelector = async () => {
  let res = await appShopSelector({ name: name.value });
  ShopList.value = res.data.datas;
};

const unitList = ref([
  {
    name: "全场盘点",
    id: 0,
  },
  {
    name: "单品盘点",
    id: 1,
  },
  {
    name: "分类盘点",
    id: 2,
  },
  {
    name: "品牌盘点",
    id: 3,
  },
]);

const selectItem = ref({});
const selectid = ref("");

const shopSelect = (e) => {
  if (selectid.value != e.id) {
    selectid.value = e.id;
  }

  selectItem.value = e;
};
const selename = ref("");
const selectTo = async () => {
  form.value.scId = selectid.value;
  showInShop.value = false;
  selename.value = selectItem.value.name;
};

const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};

//商品详情
const getProduceDet = async () => {
  console.log(id.value);
  try {
    let res = await appProductDetail({ id: id.value });
    if (res.code == 200) {
      form.value = res.data;
      fileList.value = [{ url: res.data.image }];
      form.value.checked = res.data.memberPrice > 0 ? true : false;
      purchasePricevalue.value = res.data.purchasePrice;
      checked.value = form.value.barCodeList > 0 ? true : false;
      form.value.barCodeList = form.value.barCodeList
        ? form.value.barCodeList
        : [];
      barCodeStr.value = res.data.barCode;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};

const pageslenght = ref(0);
onMounted(() => {
  getAppCategory();
  getSupplierSelector();
});
const fileList = ref([]);

// const columns = ref([]);
const showPicker = ref(false);
const showUnitPicker = ref(false);
const pickerValue = ref([]);
const purchasePricevalue = ref(0);

const onCareConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.categoryName = selectedOptions[selectedOptions.length - 1]?.name;
  form.value.categoryId = selectedValues[selectedValues.length - 1];

  pickerValue.value = selectedValues;
  showPicker.value = false;
};

const saveFun = () => {
  console.log("保存");
  console.log(form.value);
  // console.log(fileList.value[0].content);
  formMode.value.submit();
};

const onSubmit = async (values) => {
  if (!form.value.name) {
    uni.showToast({
      title: "请输入任务名称",
      icon: "none",
    });
    return;
  }
  if (!form.value.scId) {
    uni.showToast({
      title: "请选择仓库",
      icon: "none",
    });
    return;
  }
  if (form.value.takeType === "") {
    uni.showToast({
      title: "请选择盘点类型",
      icon: "none",
    });
    return;
  }

  stockObj.setForm(form.value);
  // {
  //   name: "全场盘点",
  //   id: 0,
  // },
  // {
  //   name: "单品盘点",
  //   id: 1,
  // },
  // {
  //   name: "分类盘点",
  //   id: 2,
  // },
  // {
  //   name: "品牌盘点",
  //   id: 3,
  // },
  console.log("form.value.takeType", stockObj.form);

  if (form.value.takeType === 0) {
    uni.navigateTo({
      url: "/pages/stocktaking/cerate/index",
    });
  }
  if (form.value.takeType === 1) {
    uni.navigateTo({
      url: "/pages/stocktaking/goods_sel/index",
    });
  }
  if (form.value.takeType === 2) {
    uni.navigateTo({
      url: "/pages/stocktaking/select_g/index",
    });
  }
  if (form.value.takeType === 3) {
    uni.navigateTo({
      url: "/pages/stocktaking/select_p/index",
    });
  }
};

//商品分类
const categoryList = ref([]);
const customFieldName = ref({
  text: "name",
  value: "id",
  children: "children",
});

const columns = ref([
  [112, 222, 333],
  [1212, 2121],
  [12, 2, 4.5],
]);

const pickershow = ref(false);
const pickerArr = ref([]);
const getAppCategory = async () => {
  try {
    let res = await appCategory();

    let arr = [];
    let newArr = [];
    let newArr2 = [];

    res.data.forEach((item, index) => {
      if (!item.parentId) {
        arr.push({ ...item, select: false, children: [] });
      } else {
        newArr.push({ ...item });
      }
    });
    arr.forEach((item, index) => {
      newArr.forEach((item2, index2) => {
        if (item.id == item2.parentId) {
          // item2.children = item.children || [];

          item.children.push({ ...item2, select: false, children: [] });
          newArr.splice(index2, 1);
        }
      });
    });
    arr.forEach((item, index) => {
      item.children.forEach((element, index) => {
        newArr.forEach((item2, index2) => {
          if (element.id == item2.parentId) {
            element.children.push({ ...item2, select: false });
          }
        });
      });
    });
    pickerArr.value = arr;
    columns.value[0] = arr;
    columns.value[1] = arr[0].children;
    columns.value[2] = arr[0].children[0].children;
    console.log(columns.value);
    // columns.value = arr;
  } catch (e) {}
};

//获取供应商
const supplierList = ref([]);

// const columns = ref([]);
const supplierPicker = ref(false);

const getSupplierSelector = async () => {
  try {
    let res = await supplierSelector({ pageIndex: 1, pageSize: 999 });
    supplierList.value = res.data.datas;
  } catch (e) {}
};

//商品禁用
const availableFun = async (item) => {
  if (item) {
    try {
      let res = await appProductDisable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        // showToast("禁用成功");
        uni.showToast({
          title: "禁用成功",
          icon: "none",
        });
        uni.reLaunch({ url: "/pages/goods/goods_list/index" });
      } else {
        uni.showToast({
          title: "禁用成功",
          icon: "none",
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  } else {
    try {
      let res = await appProductEnable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        uni.showToast({
          title: "启用成功",
          icon: "none",
        });
      } else {
        uni.showToast({
          title: "启用失败",
          icon: "none",
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  }
};

const selectBarCodeItem = ref("");
const selectBarCodeindex = ref("");
const isnewBarCode = ref(false);

const uUpload = ref(null);

// 监听省市区列表选择器变化
const distChangeHandler = (item) => {
  const { columnIndex, value } = item;
  console.log(columnIndex, value);
  let city = value[0].children;
  if (columnIndex === 0) {
    // 省变化更新市、区列表
    // setColumnValues(index, setVal) 设置对应列的选择值

    columns.value[1] = value[0].children;
    columns.value[2] = value[0].children[0].children;
    // uPickerRef.value.setColumnValues(1, city);
    // uPickerRef.value.setColumnValues(2, city[0].children);
  } else if (columnIndex === 1) {
    // 市变化更新区/县列表
    // uPickerRef.value.setColumnValues(2, value[1].children);
    columns.value[2] = value[1].children;
  }
};

// 确定选择服务地区
const confirmDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.categoryName = `${value[2].name}`;
  form.value.categoryId = `${value[2].id}`;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  pickershow.value = false; // 关闭弹框
};
const selecttakeType = ref("");
const confirmUnitDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.takeType = value[0].id;
  selecttakeType.value = value[0].name;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  showUnitPicker.value = false; // 关闭弹框
};

const confirmGDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.supplierName = `${value[0].name}`;
  form.value.supplierId = `${value[0].id}`;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  supplierPicker.value = false; // 关闭弹框
};

// 取消服务地区选择
const distCancel = () => {
  pickershow.value = false;
};
//无网状态
const connected = () => {
  getAppCategory();
  getSupplierSelector();
};
</script>

<template>
  <topNav
    :title="type == 'add' ? '新增盘点任务' : '修改盘点任务'"
    @save="saveFun"
    rType="save"
  ></topNav>
  <view class="goods_form">
    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <up-form
      labelPosition="left"
      labelWidth="180rpx"
      :model="form"
      :rules="rules"
      ref="form1"
    >
      <view
        style="
          padding: 0 30rpx;
          margin: 0 20rpx;
          background-color: #ffffff;
          border-radius: 15rpx;
        "
      >
        <up-form-item
          :required="true"
          label="任务名称"
          prop="name"
          borderBottom
          ref="item1"
        >
          <up-input
            v-model="form.name"
            border="none"
            placeholder="请填写任务名称"
          ></up-input>
        </up-form-item>

        <view class="line_in"></view>
        <up-form-item
          :required="true"
          label="仓库"
          prop="unit"
          borderBottom
          ref="item1"
        >
          <view
            class="categoryName-select"
            :class="selename ? 'categoryName' : ''"
            @click="showInShop = true"
            >{{ selename ? selename : "点击选择" }}
          </view>

          <template #right>
            <up-icon
              name="arrow-right"
              @click="showUnitPicker = true"
            ></up-icon>
          </template>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item
          :required="true"
          label="盘点类型"
          prop="unit"
          borderBottom
          ref="item1"
        >
          <view
            class="categoryName-select"
            :class="selecttakeType ? 'categoryName' : ''"
            @click="showUnitPicker = true"
            >{{ selecttakeType ? selecttakeType : "点击选择" }}
          </view>

          <template #right>
            <up-icon
              name="arrow-right"
              @click="showUnitPicker = true"
            ></up-icon>
          </template>
        </up-form-item>
      </view>
    </up-form>
  </view>

  <div class="foot-btn">
    <view class="foot-btn-k"
      ><van-button block type="primary" @click="onSubmit(form)">
        {{ type == "add" ? "下一步" : "下一步" }}
      </van-button></view
    >
  </div>

  <view
    class="botton-bt"
    v-if="type != 'add' && showSelect == 'admin'"
    v-permission="['manager:product:disable']"
  >
    <van-button
      type="default"
      class="botton-to"
      @click="availableFun(form.available)"
    >
      {{ form.available ? "禁用此商品" : "启用此商品" }}
    </van-button>
  </view>

  <view
    class="botton-bt"
    v-if="type != 'add' && showSelect == 'shop'"
    v-permission="['manager:product:disable']"
  >
    <van-button
      type="default"
      class="botton-to"
      @click="availableFun(form.available)"
    >
      {{ form.available ? "禁用此商品" : "启用此商品" }}
    </van-button>
  </view>

  <view style="height: 200rpx; width: 100%"></view>

  <!-- <van-popup v-model:show="supplierPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="supplierValue"
      :columns="supplierList"
      :columns-field-names="supplierFieldName"
      @confirm="onSupplierCareConfirm"
      @cancel="supplierPicker = false"
    />
  </van-popup> -->
  <!-- 
  <van-popup v-model:show="showUnitPicker" destroy-on-close position="bottom">
    <van-picker
      :columns="unitList"
      :model-value="pickerUnitValue"
      :columns-field-names="supplierUnitName"
      @confirm="onCareUnitConfirm"
      @cancel="showUnitPicker = false"
    />
  </van-popup> -->
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="pickerValue"
      :columns="columns"
      :columns-field-names="customFieldName"
      @confirm="onCareConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>

  <up-picker
    :show="pickershow"
    ref="uPickerRef"
    :columns="columns"
    keyName="name"
    @confirm="confirmDist"
    @change="distChangeHandler"
    @cancel="distCancel"
  >
  </up-picker>
  <up-picker
    :show="showUnitPicker"
    ref="uPickerRef"
    :columns="[unitList]"
    keyName="name"
    @confirm="confirmUnitDist"
    @cancel="showUnitPicker = false"
  >
  </up-picker>

  <up-picker
    :show="supplierPicker"
    ref="uPickerRef"
    :columns="[supplierList]"
    keyName="name"
    @confirm="confirmGDist"
    @cancel="supplierPicker = false"
  >
  </up-picker>

  <up-popup
    v-model:show="showInShop"
    round="10"
    @close="showInShop = false"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-content">
      <view class="popup-content-title">
        <text>{{ "仓库选择" }}</text>
      </view>
      <view class="popup-content-list">
        <view style="padding: 20rpx 30rpx" v-if="ShopList.length > 10"
          ><up-search
            shape="round"
            v-model="name"
            @search="search"
            @custom="search"
          ></up-search
        ></view>

        <scroll-view
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scroll"
        >
          <view
            class="scroll-to"
            v-for="(item, index) in ShopList"
            :key="index"
            @click="shopSelect(item, 1)"
          >
            <view
              class="scroll-to-title"
              :class="item.id == selectid ? 'scroll-to-title-sel' : ''"
            >
              <text>{{ item.name }}</text>
            </view>
            <up-icon
              v-if="item.id == selectid"
              name="checkbox-mark"
              color="#1679FB"
              size="40rpx"
            ></up-icon>
          </view>

          <view
            style="padding: 50rpx 0 50rpx 0; text-align: center; color: #adadad"
            class="scroll-to-content"
            v-if="ShopList.length == 0"
          >
            暂无数据
          </view>
        </scroll-view>
      </view>
      <view class="popup-content-btn">
        <up-button
          class="bt-qx"
          type="default"
          :plain="true"
          text="取消"
          @click="showInShop = false"
        ></up-button>
        <up-button
          type="primary"
          style="background-color: #1679fb"
          @click="selectTo()"
          text="确定"
        ></up-button>
      </view>
    </view>
  </up-popup>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
